<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportEmployeeList">导出</el-button>
          <el-button :disabled="!checkPermission('POINT-USER-ADD')" size="small" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="tableData">
          <el-table-column width="60px" label="序号" type="index" sortable="" />
          <el-table-column label="头像" prop="staffPhoto" sortable="">
            <template #default="{row}">
              <img v-imgErr="require('@/assets/common/head.jpg')" class="staffPhotoImg" :src="row.staffPhoto " alt="" @click="openQRcodeDialog(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" prop="formOfEmployment" sortable="">
            <template #default="{row}">
              {{ formatEmployment(1,2,row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" sortable="">
            <template #default="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" prop="enableState" sortable="">
            <template #default="{row}">
              <el-switch
                v-model="row.enableState"
                :active-value="1"
                :inactive-value="2"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/details/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="AssignRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployeeRows(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination :total="total" :page-size="paginationData.size" layout="prev, pager, next" @current-change="currentChange" />
        </el-row>
      </el-card>
      <employeeDialog :show-dialog="showDialog" />
      <!-- 显示二维码 -->
      <el-dialog :visible="isshowQRCode" @close="isshowQRCode=false">
        <el-row type="flex" justify="center">
          <canvas ref="refqrcode" />
        </el-row>
      </el-dialog>,
      <assignRoleDialog ref="assigRole" :ishowdialog.sync="isshowRoleDialog" />
    </div>
  </div>
</template>
<script>
import { getEmployeeListApi, delEmployee } from '@/api/employee'
import employee from '@/utils/constant/employees'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters/index'
import employeeDialog from './components/add-employee.vue'
import QRCode from 'qrcode'
import assignRoleDialog from './components/assign-role.vue'
export default {
  components: { employeeDialog, assignRoleDialog },
  data() {
    return {
      isshowRoleDialog: false,
      isshowQRCode: false,
      showDialog: false,
      total: 0, // 总条数，
      paginationData: {
        page: 1,
        size: 5
      },
      tableData: []
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async  AssignRole(id) {
      await this.$refs.assigRole.getUserDetails(id)
      this.isshowRoleDialog = true
    },
    async getEmployeeList() {
      const { rows, total } = await getEmployeeListApi(this.paginationData)

      this.tableData = rows.map(item => {
        return { ...item,
          enableState: item.enableState || 1
        }
      }) // talble中的每条数据
      this.total = total
    },
    // 分页
    currentChange(newPage) {
      // 页面切换到新的页面
      this.paginationData.page = newPage
      // 重新渲染数据
      this.getEmployeeList()
    },
    // 格式化聘用形式
    formatEmployment(row, col, cell, index) {
      // 枚举数据
      const result = employee.hireType.find(item => Number(item.id) === Number(cell))
      return result ? result.value : '未知'
    },
    // 导出员工列表
    async exportEmployeeList() {
      const { rows } = await getEmployeeListApi({
        page: 1,
        size: this.total
      })
      // 表头数据
      const header = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const data = rows.map(item => {
        return this.transferArr(item)
      })
      export_json_to_excel({
        header, data
      })
    },
    transferArr(user) {
      const newArr = []
      const header = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']

      const dict = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      header.forEach(key => {
        const enkey = dict[key]
        const values = user[enkey]
        if (enkey === 'formOfEmployment') {
          // 枚举
          const obj = employee.hireType.find(item => {
            return item.id === values
          })
          newArr.push(obj ? obj.value : '未知')
        } else if (enkey === 'correctionTime') {
          newArr.push(formatDate(values))
        } else if (enkey === 'timeOfEntry') {
          newArr.push(formatDate(values))
        } else {
          newArr.push(values)
        }
      })

      return newArr
    },
    // 删除员工
    async  delEmployeeRows(id) {
      // 二次校验
      await this.$confirm(this.$t('confirmDel'))
      // 发送请求
      await delEmployee(id)
      // 提示用户
      this.$message.success('删除成功')
      // 刷新页面
      this.getEmployeeList()
    },
    openQRcodeDialog(url) {
      this.isshowQRCode = true
      this.$nextTick(() => {
        QRCode.toCanvas(this.$refs.refqrcode, url)
      })
    }

  }

}
</script>

<style lang="scss" scoped>
.staffPhotoImg{
width: 180px;
height: 120px;
object-fit:cover;
margin:auto;
}
</style>
